import Dep from "./dep";

export default class Watcher{
    constructor(vm,expOrFn,cb){
        this.vm = vm;
        this.cb = cb;
        this.getter = parsePath(expOrFn);
        // 调用get方法，将监听器(依赖)绑定到Dep.target上
        this.value = this.get();
    }
    get(){
        Dep.target = this;
        const vm = this.vm;
        // 收集监听器(依赖)
        /**
         * 触发一次属性的getter，以此来完成监听器(依赖)的收集
         */
        let value = this.getter.call(vm, vm);
        // 收集完成后清空绑定在Dep上的监听器
        Dep.target = undefined;
        return value;
    }
    update(){
        const oldValue = this.value;
        this.value = this.get();
        this.cb.call(this.vm, this.value, oldValue);
    }
}

/**
 * Parse simple path
 * 解析简单路径
 */
 const bailRE = /[^\w.$]/;

 export function parsePath(path){
     if(bailRE.test(path)){
         return;
     }
     const segments = path.split('.');
     return function (obj){
         for(let i = 0; i < segments.length; i++){
             obj = obj[segments[i]]
         }
     }
 }